package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.entity.GeneralGoodsCategory
import com.zxy.supplier_system.server.service.GeneralGoodsCategoryService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/generalGoodsCategories")
class GeneralGoodsCategoryController(
    private val generalGoodsCategoryService: GeneralGoodsCategoryService,
) {

    data class GeneralGoodsCategoryNodeResponse(
        val id: Int,
        val name: String,
        val children: List<GeneralGoodsCategoryNodeResponse>,
    ){
        companion object{
            fun flatCategoriesToNodeTree(generalGoodsCategories: List<GeneralGoodsCategory>):List<GeneralGoodsCategoryNodeResponse>{
                return generalGoodsCategories.filter { it.parent==null }.map {
                    buildTreeNodeListWithFlatCategories(it,generalGoodsCategories)
                }
            }
            fun buildTreeNodeListWithFlatCategories(node: GeneralGoodsCategory,generalGoodsCategories: List<GeneralGoodsCategory>): GeneralGoodsCategoryNodeResponse {
                val children = generalGoodsCategories.filter { it.parent == node }

                return GeneralGoodsCategoryNodeResponse(
                    node.id!!,node.name,
                    children.map { buildTreeNodeListWithFlatCategories(it, generalGoodsCategories) }
                )
            }
        }
    }

    @GetMapping("tree")
    fun allCategories(): List<GeneralGoodsCategoryNodeResponse>{
        return this.generalGoodsCategoryService.findAllTree()
    }

}